package net.lainiao.zhihu.reptitle;

import net.lainiao.zhihu.common.Common;
import net.lainiao.zhihu.model.Zhihudaan;
import net.lainiao.zhihu.model.ZhihuwentiWithBLOBs;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.xml.sax.SAXException;

import java.io.IOException;
import java.util.ArrayList;


/**
 * Created by Administrator on 2016/1/14.
 */
public class ZhihuQuestion {
    /**
     * 解析问题和其中的答案
     *
     * @param document
     * @return
     */
    public static ZhihuwentiWithBLOBs parseQuestion(Document document) {
        ZhihuwentiWithBLOBs zhihuwenti = new ZhihuwentiWithBLOBs();
        zhihuwenti.setId(Common.getNewUUID());
        Element element1 = document.select("#zh-question-title").first();
        Element element2 = document.select("#zh-question-detail").first();
        zhihuwenti.setTitle(element1.html());
        zhihuwenti.setDetails(element2.html());
        zhihuwenti.setZhihudaans(new ArrayList<Zhihudaan>());
        Elements elements = document.select(".zm-item-answer.zm-item-expanded");
        for (Element element : elements) {
            Element ups = element.select(".up").first().select(".count").first();
            String upint=ups.html();
            if(upint.indexOf("K")>-1){
                upint=upint.replace("K","");
                upint+="000";
            }
            int zan = Integer.parseInt(upint);
            String daan = element.select(".zm-item-rich-text.js-collapse-body").first().html();
            Zhihudaan zhihudaan = new Zhihudaan();
            zhihudaan.setId(Common.getNewUUID());
            zhihudaan.setZhwtId(zhihuwenti.getId());
            zhihudaan.setZan(zan);
            zhihudaan.setAnswer(daan);
            int quanzhong = daan.length();
            if(zan==0){
                quanzhong=0;
            }else{
                quanzhong=quanzhong/zan;
            }

            zhihudaan.setQuanzhong(quanzhong);
            zhihuwenti.getZhihudaans().add(zhihudaan);
        }
        return zhihuwenti;
    }

    /**
     * 解析问题和其中的答案
     *
     * @param url
     * @return
     */
    public static ZhihuwentiWithBLOBs parseQuestion(String url) throws IOException, SAXException, InterruptedException {
        Document document = HtmlCommon.getDocument(url);
        return parseQuestion(document);
    }
}
